package com.titan.core.utils.db;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import com.titan.core.base.BaseRowMapper;
import com.titan.core.utils.data.FormatUtils;

/**
 * @author 周成功
 * @email 86898837@qq.com
 * @date 2020年02月20日
 */
public class JdbcUtils {
    private static Log log = LogFactory.getLog(JdbcUtils.class);
    private static volatile DataSource dataSource = null; 

    
    public static void setDataSource(DataSource ds) throws IOException {
        dataSource = ds;
    }
    public static DataSource getDataSource() throws IOException {
        DataSource ds = DataSourceUtils.getCurrentDataSource();
        if(ds==null) {
            return dataSource;
        }
        return ds;
    }    
    private static JdbcTemplate getJdbcTemplate() throws IOException {
        DataSource ds = getDataSource();
        JdbcTemplate jt = new JdbcTemplate();
        jt.setDataSource(ds);
        return jt;
    }
    
    
    public static int update(String sql, Object...args) throws DataAccessException, IOException {
        log.debug("[sql] "+sql);
        log.debug("[arg] "+FormatUtils.toString(args));
        int ret = getJdbcTemplate().update(sql, args);
        log.debug("[ret] 影响记录数："+ret);
        return ret;
    }
    public static int update(String sql) throws DataAccessException, IOException {
        log.debug("[sql] "+sql);
        int ret = getJdbcTemplate().update(sql);
        log.debug("[ret] 影响记录数："+ret);
        return ret;
    }    
    
    public static List<Map<String, Object>> queryToList(String sql, Object...args) throws DataAccessException, IOException {
        log.debug("[sql] "+sql);
        log.debug("[arg] "+FormatUtils.toString(args));
        BaseRowMapper.clear();
        List<Map<String, Object>> list = null;
        if( (args==null)||(args.length==0) ) {
            list = getJdbcTemplate().queryForList(sql);
        } else {
            list = getJdbcTemplate().queryForList(sql, args);
        }
        int count = 0;
        if(list!=null) {
            count = list.size();
        }
        log.debug("[ret] 查询到记录数："+count);
        return list;
    }    
    
}
